<?php
namespace app\index\model;

use app\ux\UtilDb;
use think\Model;
use think\Session;

class Logs extends Model
{

    //关闭update_time字段自动写入
    //
    protected $updateTime = false;

    //重写initialize()
    //
    protected function initialize()
    {
        parent::initialize();
        $this->table = 'logs';
    }

    /**
     * 获取请求变量
     *
     * @return   array 请求变量数组
     */
    public function getReqInfo()
    {
        //获取请求对象模块、控制器、操作名称、IP、参数
        //
        $request = \think\Request::instance();

        $data['ip']    = $request->ip();
        $data['param'] = $request->param();

        $data['controller'] = $request->controller();
        $data['module']     = $request->module();
        $data['action']     = $request->action();

        return $data;
    }


    /**
     * 保存日志
     *
     * @param    array $output 返回信息
     * @param    boolean $authorized 登录标志
     * @return   void
     */
    public function doLog($rtn, $authorized = true)
    {

        //获取请求
        //
        $data = $this->getReqInfo();

        //非转义转码
        //
        $data['param']  = json_encode($data['param'], JSON_UNESCAPED_UNICODE);
        $data['result'] = json_encode($rtn, JSON_UNESCAPED_UNICODE);

        //判断是授权日志还是事件日志
        //
        if ($authorized) {

            //获取操作用户信息
            //
            $user               = Session::get('CURRENT_USER');
            $data['staff_id']   = $user['user'];
            $data['staff_name'] = $user['cname'];
            $data['role_name']  = $user['role_name'];
        }

        $data['create_time'] = date("Y-m-d H:i:s");

        //过滤请求数组中非数据表数据
        //
        $res = self::allowField(true)
            ->isUpdate(false)
            ->save($data);

        return $res ? $res : false; 
    }


    /**
     * 清空日志
     *
     * @return   [null]
     */
    public function clearLog()
    {
        try {
            UtilDb::clearTable($this->table);
        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
}
